package com.interview.javabase.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description: 读写锁
 *
 * @author: zhangshuguang@vichain.com
 * @date: 2019/06/14 13:49
 */
public class Demo12 {

    private volatile Map<String,Object> map  = new HashMap<>();

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    public static void main(String[] args) throws InterruptedException {
        Demo12 demo12 = new Demo12();

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                demo12.put(finalI +"",finalI+"");
            },i+"").start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                demo12.get(finalI +"");
            },i+"").start();
        }

    }

    private void put(String key , Object value){

        reentrantReadWriteLock.writeLock().lock();
        try {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + "正在写入" + key);
            try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            map.put(key,value);
            System.out.println(thread.getName() + "写入完成");
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }

    }

    private void get(String key ){
        reentrantReadWriteLock.readLock().lock();
        try {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + "正在读取");
            try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            Object result = map.get(key);
            System.out.println(thread.getName() + "读取完成"+result);
        }finally {
            reentrantReadWriteLock.readLock().unlock();
        }

    }

}
